﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Drawing;

namespace Turtle8
{
    class PostImagesManager
    {
        private IList<PostImage> list = new List<PostImage>();
        PostPanel postPanel;

        int currentIndex;
        public PostImagesManager(PostPanel postPanel)
        {
            this.postPanel = postPanel;

            //setting the images component
            SqlCommand selectCmd = SqlManager.SqlCommandFactory("Select * from [TahasukaPostImages] WHERE (startDate=@startDate)");
            selectCmd.Parameters.Add("@startDate", SqlDbType.Date).Value = postPanel.StartDate;

            //inserting new PostImage object to the postImageList.
            SqlDataReader reader = selectCmd.ExecuteReader();
            while (reader.Read())
            {
                MemoryStream ms = new MemoryStream((byte[])reader["image"]);
                Image img = Image.FromStream(ms, true, true);
                list.Add(new PostImage(img, (string)reader["caption"], list.Count));
            }

            reader.Close();

            if (list.Count > 0)
                currentIndex = 0;
            else currentIndex = -1;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public PostImage addNewImage(string fileName) 
        {
            PostImage newImage = new PostImage(Image.FromFile(fileName), list.Count);
            list.Add(newImage);
            currentIndex = list.Count - 1;

            return newImage;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="postImage"></param>
        public PostImage deleteImage(PostImage postImage) 
        {
            list.Remove(postImage);
            if (list.Count == 0)
                currentIndex = -1;

            //deleting the image from the database.
            string deleteStr = "DELETE FROM [TahasukaPostImages] WHERE (id=@id AND startDate=@startDate AND postName=@postName)";
            SqlCommand deleteCmd = SqlManager.SqlCommandFactory(deleteStr);
            deleteCmd.Parameters.Add("@id", SqlDbType.Int).Value = postImage.ID;
            deleteCmd.Parameters.Add("@postName", SqlDbType.NVarChar).Value = postPanel.PostName;
            deleteCmd.Parameters.Add("@startDate", SqlDbType.Date).Value = postPanel.StartDate;

            deleteCmd.ExecuteNonQuery();

            return getPrevious();
        }

        public PostImage getNext()
        {
            if (currentIndex == -1)
                return null;
            else if ((list.Count - 1) == currentIndex) //last element
            {
                currentIndex = 0;
                return list[0];
            }
            else
            {
                currentIndex += 1;
                return list[currentIndex];
            }
        }
        public PostImage getPrevious() 
        {
            if (currentIndex == -1)
                return null;
            else if (currentIndex == 0) //first element
            {
                currentIndex = list.Count - 1;
                return list[currentIndex];
            }
            else
            {
                currentIndex -= 1;
                return list[currentIndex];
            }




        
        }

        public PostImage editCaption(PostImage postImage)
        {
            int i;
            for (i = 0; i < list.Count; i++)
                if (list.ElementAt(i).ID == postImage.ID)
                    break;

            list.ElementAt(i).Caption = postImage.Caption;
            return list.ElementAt(i);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public void updateDB() 
        {
            foreach (PostImage item in list)
            {
                item.updateDatabase(postPanel.PostName, postPanel.StartDate);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public void updateDB(string oldPostName, string newPostName)
        {
            string updateStr = "UPDATE [TahasukaPostImages] SET postName=@newPostName WHERE startDate=@startDate AND postName=@oldPostName";
            SqlCommand updateCmd = SqlManager.SqlCommandFactory(updateStr);
            updateCmd.Parameters.Add("@newPostName", SqlDbType.NVarChar).Value = newPostName;
            updateCmd.Parameters.Add("@oldPostName", SqlDbType.NVarChar).Value = oldPostName;
            updateCmd.Parameters.Add("@startDate", SqlDbType.Date).Value = postPanel.StartDate;
            updateCmd.ExecuteNonQuery();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public bool deleteAllImages() 
        {

            foreach (PostImage item in list)
                deleteImage(item);

            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public PostImage getFirst()
        {
            if (list.Count == 0)
                return null;
            else return list[0];
        }

        public int getCount()
        {
            return list.Count;
        }

        public PostImage setCaption(string caption)
        {
            if (currentIndex != -1)
            {
                list[currentIndex].Caption = caption;
                return list[currentIndex];
            }
            return null;
        }
    }


    class PostImage
    {
        public readonly static String EmptyCaption = "כרגע אין הערה";
        public readonly static String NoImage = "תמונה טרם נבחרה";
        Image image;
        int databaseID;
        bool isInserted;

        public int ID
        { get { return databaseID; } }
        public Image Image
        { get { return image; } }

        public string Caption
        { get; set; }

        //this Ctor is called directly for each already exists image in database
        public PostImage(Image image, string caption, int imageID)
        {
            this.image = image;
            this.Caption = caption;
            this.databaseID = imageID;
            this.isInserted = true;
        }

        //this Ctor is called when a new image is creates by the user
        public PostImage(Image image, int imageID)
            : this(image, PostImage.EmptyCaption, imageID)
        {
            isInserted = false;
        }

        public bool updateDatabase(string postName, DateTime startDate)
        {
            if (!isInserted)
            {
                //inserting the new image to the database.
                string insertStr = "INSERT INTO [TahasukaPostImages] VALUES (@id,@postName, @startDate, @image, @caption)";
                SqlCommand insertCmd = SqlManager.SqlCommandFactory(insertStr);
                insertCmd.Parameters.Add("@id", SqlDbType.NVarChar).Value = databaseID;
                insertCmd.Parameters.Add("@postName", SqlDbType.NVarChar).Value = postName;
                insertCmd.Parameters.Add("@startDate", SqlDbType.Date).Value = startDate;
                insertCmd.Parameters.Add("@image", SqlDbType.VarBinary).Value = CompanyManager.imageToByteArray(image);
                insertCmd.Parameters.Add("@caption", SqlDbType.NVarChar).Value = Caption;

                insertCmd.ExecuteNonQuery();
                isInserted = true;
                return true;
            }
            else
            {
                string updateStr = "UPDATE [TahasukaPostImages] SET image=@image,caption=@caption WHERE id=@databaseID AND postName=@postName AND startDate=@startDate";
                SqlCommand updateCmd = SqlManager.SqlCommandFactory(updateStr);
                updateCmd.Parameters.Add("@databaseID", SqlDbType.NVarChar).Value = databaseID;
                updateCmd.Parameters.Add("@postName", SqlDbType.NVarChar).Value = postName;
                updateCmd.Parameters.Add("@startDate", SqlDbType.Date).Value = startDate;
                updateCmd.Parameters.Add("@image", SqlDbType.VarBinary).Value = CompanyManager.imageToByteArray(image);
                updateCmd.Parameters.Add("@caption", SqlDbType.NVarChar).Value = Caption;

                updateCmd.ExecuteNonQuery();
                return true;
            }
        }

    }
}
